package et.six.eta.View;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.SaveCallback;
import com.bumptech.glide.Glide;

import et.six.eta.R;

public class Dialog extends AlertDialog implements View.OnClickListener {
    ImageView imageView;
    TextView detail_price, detail, detail_name;
    String food_name, food_price, food_img, food_detail, food_id;
    Context context;
    Button button;

    public Dialog(@NonNull Context context, String food_name, String food_price, String food_img, String food_detail, String food_id) {
        super(context);
        View view = View.inflate(context, R.layout.activity_detail, null);
        this.setView(view);
        this.food_name = food_name;
        this.food_price = food_price;
        this.food_img = food_img;
        this.food_detail = food_detail;
        this.context = context;
        this.food_id = food_id;

        imageView = view.findViewById(R.id.detail_img);
        detail = view.findViewById(R.id.detail);
        detail_name = view.findViewById(R.id.detail_name);
        detail_price = view.findViewById(R.id.detail_price);
        button = view.findViewById(R.id.detail_button);

        Glide.with(context).load(food_img).into(imageView);
        detail.setText(food_detail);
        detail_name.setText(food_name);
        detail_price.setText(food_price);

        button.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        AVObject todo = AVObject.createWithoutData("FoodList", food_id);
        todo.put("food_isPay", 1);
        todo.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    Toast.makeText(context, "购买成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "购买失败", Toast.LENGTH_SHORT).show();
                    Dialog.this.dismiss();
                }
            }
        });


        AVObject avObject = new AVObject("PurchaseRecord");
        avObject.put("food_name", food_name);
        avObject.put("food_price", food_price);
        avObject.put("food_img", food_img);
        avObject.put("food_detail", food_detail);
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    Dialog.this.dismiss();
                } else {
                    Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                    Dialog.this.dismiss();
                }
            }
        });
    }

}
